<?php

namespace Core\annotationhandlers;

use Core\annotations\RequestMapping;
use Core\BeanFactory;
use Core\init\DecorateCollector;
use Core\init\RouterCollector;

return [
    RequestMapping::class => function (\ReflectionMethod $method, $instance, RequestMapping $mapping) {
        $path = $mapping->path;
        $requestMethod = count($mapping->method) > 0 ? $mapping->method : ["GET"];
        $router_collector = BeanFactory::getBean(RouterCollector::class);
        /**@var $router_collector RouterCollector* */
        $router_collector->addRouter($requestMethod, $path, function ($params, $ext_params) use ($method, $instance) {
            $inputParams = [];
            //获取方法的反射参数
            $reflect_params = $method->getParameters();
            foreach ($reflect_params as $reflect_param) {
                //获取反射参数名
                $param_name = $reflect_param->getName();
                //判断传入的参数是否包含
                if (isset($params[$param_name])) {
                    $inputParams[] = $params[$param_name];
                } else {
                    foreach ($ext_params as $ext_param) {
                        if ($reflect_param->getClass() && $reflect_param->getClass()->isInstance($ext_param)) {
                            $inputParams[] = $ext_param;
                            goto end;
                        }
                    }
                    //没有的话 需要设置默认值
                    $inputParams[] = false;
                }
                end:
            }
            $collector = BeanFactory::getBean(DecorateCollector::class);
            return $collector->exec($method, $instance, $inputParams);
            // invokeArgs 无key名 需对应参数个数
//            return $method->invokeArgs($instance, $inputParams);
        });
        return $instance;
    }
];
